<template >
<div class="tcflefttofactory">
  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}}<i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">TCF付尾款给工厂</span>
    </el-breadcrumb>
  </div>

  <el-tabs v-model="editableTabsValue" type="card">
    <el-tab-pane :key="item.name" v-for="item in editableTabsFixed" :label="item.title" :name="item.name">
      <quality-assurance :bus="bus" :editable="editable" @fromQA="updateData" :datas="saveData.tcflefttofactory_qualityassurance" v-if="item.name === '1'"/>
      <left-apply :bus="bus" :editable="editable" @fromLA="updateData" :datas="saveData.tcflefttofactory_leftapply"  v-else  />
    </el-tab-pane>
  </el-tabs>



  <div class="tcleftftofactory-bottom">
    <fixed-form v-if="hasBind" ref="fixedForm" :saveAndSend="saveAndSend" :editable="editable" :datas="allData" :sendMenus="sendMenus" processName="tcflefttofactory" />
    <fixed-form v-else  ref="fixedForm" :saveAndSend="false" :editable="false" :datas="allData" :sendMenus="sendMenus" processName="tcflefttofactory" />
  </div>

</div>
</template>

<script>

import Vue from 'vue';
import qualityAssurance from './components/qualityAssurance.vue';
import leftApply from './components/leftApply.vue';

import fixedForm from '../common/fixedForm.vue'

import {
  getSendMenus,
  getData,
} from '@/server/initiatingprocess'
import {
  getStore,
  setStore
} from '@/assets/js/common'

export default {
  beforeRouteEnter(to, from, next) {

    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }

    next(vm => {

      if (to.query.tab){

        switch (to.query.tab) {
          case '1':
          vm.editableTabsValue = '1';
          break;
          case '2':
          vm.editableTabsValue = '2';
        }
        // vm.$message({
        //   message: '请先绑定订单，否则无法保存和发送',
        //   type: 'warning',
        //   duration: 3000,
        //   showClose: true
        // });
      }

      //从其他位置跳转过来
      if (to.query.dTab) {
        vm.editableTabsValue = '' + to.query.dTab;
        vm.processNumber = parseInt(to.query.itemStatus);

        vm.hasBind = true;
        vm.bus.$emit('has-bind');

        if (to.query.isHive == 1) {
          let params = {
            flowId: to.query.flowId,
            currNodeId: to.query.currNodeId
          };

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {

            let data = response.data.datas[0];


            if (data.tcflefttofactory_qualityassurance.tq_table1.length === 0){
              data.tcflefttofactory_qualityassurance.tq_table1 = [{
                tq_table1_products: '',
                tq_table1_description: '',
                tq_table1_quantity: 0
              }];
            }

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              if ((k == 'tl_checkedPayMethods') || ( k == 'tl_thisPaymentTypes') || (k == 'tl_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });


            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }

            let approvalIndex, approvalFullName, names = [], originApprovals = _.cloneDeep(vm.saveData.originApprovals);

            if (data.role) {

              vm.editable = data.role.DEFAULT == 'W' ? true : false;
              vm.saveAndSend = vm.editable;

              let copyApprovals = _.cloneDeep(data.approvals);

              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              vm.$set(vm.saveData, "originApprovals", originApprovals);
              vm.$set(vm.saveData, "isSalesMan", false);
            } else {
              vm.$set(vm.saveData, "isSalesMan", true);
            }

            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.allData = _.cloneDeep(vm.saveData);
            });
          });

        } else {

          let params = {
            flowId: to.query.flowId,
            currNodeId: to.query.currNodeId
          };

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {

            let data = response.data.datas[0];

            /*
            let data =   {
                "tcflefttofactory_leftapply": {
                    "id": 5,
                    "createTime": 1529894137000,
                    "modifyTime": null,
                    "formInstId": 92,
                    "attachedFileList": [
                        {
                            "id": 27,
                            "createTime": 1529894135000,
                            "modifyTime": 1529894137000,
                            "fileName": "attached/1529894135135_98.png",
                            "type": 2,
                            "status": 1,
                            "formInstId": 92,
                            "tabName": "tcflefttofactory_leftapply",
                            "tabId": 5,
                            "customerId": null,
                            "realFileName": "98.png"
                        }
                    ],
                    "tl_applicant": "zhaosi",
                    "tl_applicationDate": "2018-06-28",
                    "tl_applicationDepart": "业务一部",
                    "tl_checkedPayMethods": "1",
                    "tl_collectionCompany": "桂林智神信息技术有限公司",
                    "tl_collectionBank": "桂林智神信息技术有限公司",
                    "tl_collectionAccount": "6223 6721 0572",
                    "tl_paymentAmount": "20000",
                    "tl_paymentBigAmount": "10000",
                    "tl_paymentAbstract": "",
                    "tl_businessType": "O/A",
                    "tl_businessTypeoptions": null,
                    "tl_signDate": "2017-12-01",
                    "tl_contractAmount": "20000",
                    "tl_payedMount": "30000",
                    "tl_thisPaymentTypes": "0",
                    "tl_nonPaymentTypes": "0",
                    "tl_thisPaymentAmount": "222220",
                    "tl_nonPaymentAmount": "222220",
                    "tl_dtcNO": "ZS20171203F"
                },
                "tcflefttofactory_qualityassurance": {
                    "id": 5,
                    "createTime": 1529894137000,
                    "modifyTime": null,
                    "formInstId": 92,
                    "attachedFileList": [],
                    "tq_totalMoney": null,
                    "tq_bindFContracts": "ZS20171203",
                    "tq_bindDContracts": "ZS20171203F",
                    "tq_contractno": "ZS20171203",
                    "tq_date": "2017-12-01",
                    "tq_buyer": "OOO \"TSIFROMARKET\"",
                    "tq_address": "M A Y A K O V S K O G O S T R E E T , 1 6 0 ,KRASNODAR, KRASNODARSKIY KRAY,RUSSIAN FEDERATION",
                    "tq_table1_number": "2200",
                    "tq_tel": "50911255",
                    "buyerName": "OOO \"TSIFROMARKET\"",
                    "orderCode": "NO.DD2018051800112",
                    "tq_table1": [
                        {
                            "id": 9,
                            "createTime": 1529894137000,
                            "modifyTime": null,
                            "formInstId": 92,
                            "tcffqId": 5,
                            "tq_table1_description": "sgsgsg",
                            "tq_table1_quantity": "2000"
                        },
                        {
                            "id": 10,
                            "createTime": 1529894137000,
                            "modifyTime": null,
                            "formInstId": 92,
                            "tcffqId": 5,
                            "tq_table1_description": "sgsgsgsgs",
                            "tq_table1_quantity": "200"
                        }
                    ]
                },
                "formInstId": 92,
                "flowId": 4,
                "formId": 4,
                "formServiceName": "tcflefttofactory",
                "bindingFormInstId": null,
                "orderCode": "NO.DD2018051800112",
                "approvals": [],
                "role": [
                    {
                        "id": 124,
                        "createTime": 1525752211000,
                        "modifyTime": null,
                        "formId": 4,
                        "flowId": 4,
                        "flowNodeId": 15,
                        "flowNodeName": "业务填报",
                        "itemName": "tcflefttofactory_qualityassurance",
                        "permission": "W"
                    },
                    {
                        "id": 125,
                        "createTime": 1525752211000,
                        "modifyTime": null,
                        "formId": 4,
                        "flowId": 4,
                        "flowNodeId": 15,
                        "flowNodeName": "业务填报",
                        "itemName": "tcflefttofactory_leftapply",
                        "permission": "W"
                    },
                    {
                        "id": 126,
                        "createTime": 1525752211000,
                        "modifyTime": null,
                        "formId": 4,
                        "flowId": 4,
                        "flowNodeId": 15,
                        "flowNodeName": "业务填报",
                        "itemName": "item_04_01",
                        "permission": "R"
                    },
                    {
                        "id": 127,
                        "createTime": 1525752211000,
                        "modifyTime": null,
                        "formId": 4,
                        "flowId": 4,
                        "flowNodeId": 15,
                        "flowNodeName": "业务填报",
                        "itemName": "item_04_02",
                        "permission": "R"
                    },
                    {
                        "id": 128,
                        "createTime": 1525752211000,
                        "modifyTime": null,
                        "formId": 4,
                        "flowId": 4,
                        "flowNodeId": 15,
                        "flowNodeName": "业务填报",
                        "itemName": "item_04_03",
                        "permission": "R"
                    }
                ]
            };
            */

            /**
             * 处理表格数据，后端返回空数组的情况
             */
            if (data.tcflefttofactory_qualityassurance.tq_table1.length === 0){
              data.tcflefttofactory_qualityassurance.tq_table1 = [{
                tq_table1_products: '',
                tq_table1_description: '',
                tq_table1_quantity: 0
              }];
            }

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              if ((k == 'tl_checkedPayMethods') || ( k == 'tl_thisPaymentTypes') || (k == 'tl_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }

            let approvalIndex, approvalFullName, names = [],
            originApprovals = _.cloneDeep(vm.saveData.originApprovals);

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.$set(vm.roles, e.itemName, e.permission);
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                  }
                }
              });


              vm.editable = vm.roles.tcflefttofactory_qualityassurance == 'W' ? true : false;
              vm.saveAndSend = true;

              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      originApprovals[i].approval_id =  '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                originApprovals[approvalIndex].rw = 'W';
                originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }

              vm.$set(vm.saveData, "originApprovals", originApprovals);
              vm.$set(vm.saveData, "isSalesMan", false)
            } else {
              vm.$set(vm.saveData, "isSalesMan", true)
            }

            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.allData = _.cloneDeep(vm.saveData);
            });
          });
        }
      }
    });
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (getStore("flow4-save-status") === 'unsave'){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  created() {
    setStore("flow4-save-status", "unsave");
    this.allData = _.cloneDeep(this.saveData);

    this.bus = new Vue();
    this.bus.$on('bind-new-ftc', (data) => {
      this.hasBind =  data;
    });
  },
  data() {
    return {
        saveData: {
          hasSaved: false,
          relationFormInstId: [], //关联订单
          isSalesMan: true,

          newApprovalName: '',

          approvalNames: [
            "业务领导审批尾款付款申请单",
            "风控审批尾款付款申请单",
            "财务审批尾款付款申请单"
          ],

          newApproval: {
            "approval_opinion":"",
            "approval_username":"",
            "approval_time":"",
            "approval_div_name": ""
          },

          prevApprovals: [],
          remainApprovals: [],

          //该流程中的所有审批项
          originApprovals:[{
            "approval_opinion":"",
            "approval_username":"",
            "approval_time":"",
            "approval_div_name":"业务领导审批尾款付款申请单",
            "rw": 'R',
            item: 'item_04_01',
          }, {
            "approval_opinion":"",
            "approval_username":"",
            "approval_time":"",
            "approval_div_name":"风控审批尾款付款申请单",
            "rw": 'R',
            item: 'item_04_02',
          }, {
            "approval_opinion":"",
            "approval_username":"",
            "approval_time":"",
            "approval_div_name":"财务审批尾款付款申请单",
            "rw": 'R',
            item: 'item_04_03',
          }],


          tcflefttofactory_qualityassurance: {
            id: '',
            formInstId: '',
            attachedFiles: [],
            tq_bindFContracts: [], //绑定的外贸合同
            tq_bindDContracts: [], //绑定的内贸合同
            buyerName: '',
            orderCode: '',

            bindingFormInstId: '',
            
            tq_contractno: '',
            tq_date: '',
            tq_buyer: '',
            tq_address: '',
            tq_tel: '',
            tq_table1_number: '',
            tq_table1: [
              {
                tq_table1_products: '',
                tq_table1_description: '',
                tq_table1_quantity: 0
              }
            ]
          },
          tcflefttofactory_leftapply: {
            id: '',
            formInstId: '',
            attachedFiles: [],
            tl_applicant: '',
            tl_applicationDate: '',
            tl_applicationDepart: '',
            tl_checkedPayMethods: [],

            tl_payCompany: '',
            tl_payBank: '',
            tl_payAccount: '',

            tl_collectionCompany: '',
            tl_collectionBank: '',
            tl_collectionAccount: '',
            tl_paymentAmount: 0,
            tl_paymentBigAmount: 0,
            tl_paymentAbstract: '',
            tl_businessType: '垫税',
            tl_signDate: '',
            tl_contractAmount: 0,
            tl_payedMount: 0,
            tl_thisPaymentTypes: [],
            tl_nonPaymentTypes: [],
            tl_thisPaymentAmount: 0,
            tl_nonPaymentAmount: 0,
            tl_dtcNO: ''
          },
        },
        allData: {},
        roles: {},
        sendMenus: [],
        isShowItem: false,
        isShowSpan: false,
        bus: null,
        hasBind: false,
        editable: true,
        saveAndSend: true,
        process: ['待发事项', '待办事项', '已办事项','发起流程'],
        processNumber: 3,
        editableTabsValue: '1',
        relation: true, //决定表格之间是否有关联，当从服务器端获取数据时，所有的表格都不会有关联,
        editableTabsFixed: [{
          name: '1',
          title: '质量确认函',
          formId: 'qualityassurance'
        }, {
          name: '2',
          title: '尾款付款申请单&通知书',
          formId: 'leftapply'
        }]
    }
  },
  props: {
    formIdStart: {
      type: String,
      required: true
    }
  },
  mounted() {
    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';

    getSendMenus({
      'flowId': 4
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;
  },

  beforeDestroy(){
    setStore("flow4-save-status", "unsave");
  },

  methods: {
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;
      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },

    /**
     * 更新所有需要提交的数据
     * @param {String} key
     * @param {Object} data 
     */
    updateData(key, data){
      let temp = _.cloneDeep(this.allData);
      temp[key] = data;
      this.allData = temp;
    }
  },
  components: {
    qualityAssurance,
    leftApply,
    fixedForm
  }
}
</script>

<style lang="scss">
.tcflefttofactory {
    padding: 20px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .tcleftftofactory-bottom {
        margin-top: 20px;
        border: 1px solid #999;
    }
}
</style>
